package com.web.servlet;

import com.bean.Goods;
import com.service.GoodsService;
import com.service.impl.GoodsServiceImpl;
import javafx.util.converter.LocalDateTimeStringConverter;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

/**
 * 添加good数据
 */
@WebServlet("/addGood")
@MultipartConfig
public class addGoodServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String gname = request.getParameter("gname");
        String gprice = request.getParameter("gprice");
        String gstock = request.getParameter("gstock");
        String date = request.getParameter("maintainDate");
        String classify = request.getParameter("classify");
        String gdescribe = request.getParameter("gdescribe");
        Part gimg = request.getPart("gimg");
        //获取文件名
        String fileName = gimg.getSubmittedFileName();
        //获取随机ID
        UUID uuid = UUID.randomUUID();
        //获取当前时间的时间戳
        long time = new Date().getTime();
        //给图片名添加唯一名
        fileName = uuid.toString()+time+fileName;
        //给文件路径添加对应时间、
        LocalDate localDate = LocalDate.now();
        String contextPath = request.getContextPath();
        System.out.println("contextPath = " + contextPath);
        //存放数据库的路径
        String path = "img/tou/"+localDate.getYear()
                +"/"+localDate.getMonthValue()+"/"+localDate.getDayOfMonth()+"/"+fileName;
        //创建文件路径用于保存图片
        File file = new File(getServletContext().getRealPath("/"+path));
        //判断父级目录是否存在
        if(!file.getParentFile().exists()){
            file.mkdirs();
        }
        //将文件放入指定位置
        gimg.write(file.toString());


        Goods good = new Goods(0,gname,path,Double.parseDouble(gprice),Long.parseLong(gstock),date,classify,gdescribe);
        GoodsService goodsService = new GoodsServiceImpl();
        //获得session
        HttpSession session = request.getSession();
        if(goodsService.add(good))
            session.setAttribute("operateFruit","添加成功");
        else
            session.setAttribute("operateFruit","添加失败");
        request.getRequestDispatcher("goods").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
